package ichubcache

import (
	"gitee.com/ichub/goconfig/common/base/basedto"
	"gitee.com/ichub/goconfig/common/base/baseiface"
	"gitee.com/ichub/goconfig/common/base/baseutils"
	"gitee.com/ichub/goconfig/common/base/baseutils/goutils"
	"github.com/patrickmn/go-cache"
	"time"
)

func FindMetaCacheSet[T any](value baseiface.IcacheKey) *T {
	var typename = baseutils.FindNameOfIface(value)
	if md, ok := FindBeanMetaCache().CacheGetType(value, typename); ok {
		return md.(*T)
	}
	FindBeanMetaCache().CacheSetType(value, typename)

	if md, ok := FindBeanMetaCache().CacheGetType(value, typename); ok {
		return md.(*T)
	}
	goutils.Error("FindMetaCache Eror, cacheKey is ", value.CacheKey())
	return nil
}

type MetaCache struct {
	basedto.BaseEntitySingle

	cache    *IchubCache
	timeout  time.Duration
	typeName string
}

func NewMetaCache() *MetaCache {

	var mcache = &MetaCache{
		cache:   NewIchubCache("MetaCache:"),
		timeout: cache.NoExpiration,
	}
	var typeName = baseutils.FindNameOfIface(mcache)
	mcache.cache.Pkey = typeName
	return mcache
}

func (this *MetaCache) CacheGet(Key baseiface.IcacheKey) (any, bool) {
	v, found := this.cache.Get(Key.CacheKey())
	if found {
		return v, found
	}
	return nil, false
}

func (this *MetaCache) CacheSet(Key baseiface.IcacheKey) {
	this.cache.Set(Key.CacheKey(), Key, this.timeout)

}
func (this *MetaCache) CacheGetType(Key baseiface.IcacheKey, stype string) (any, bool) {
	v, found := this.cache.Get(Key.CacheKey() + stype)
	if found {
		return v, found
	}
	return nil, false
}

func (this *MetaCache) CacheSetType(Key baseiface.IcacheKey, stype string) {
	this.cache.Set(Key.CacheKey()+stype, Key, this.timeout)

}
